package com.shengde.jinwawaforleader.model.myJob.adapter;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.myJob.classList.WorkOfTeacherActivity;
import com.shengde.jinwawaforleader.model.myJob.classStatus.AlbumImageBrowserActivity;
import com.shengde.jinwawaforleader.model.myJob.classStatus.ClassStatusActivity;
import com.shengde.jinwawaforleader.model.myJob.classStatus.ClassStatusItemDetailActivity;
import com.shengde.jinwawaforleader.model.myJob.classStatus.LookPeopleNumActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProClassStatus;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGood;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGoodCancle;
import com.shengde.jinwawaforleader.network.protocolbean.ProVideoShowClickGood;
import com.shengde.jinwawaforleader.network.protocolbean.ProVideoShowClickGoodCancle;
import com.shengde.jinwawaforleader.utils.DateUtil;
import com.shengde.jinwawaforleader.utils.UmengShareUtil;
import com.shengde.jinwawaforleader.views.CircleImageView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * /*
 * Created by Administrator on 2016/9/9 0009.
 */
public class ClassStatusAdapter extends BaseAdapter {
    private static final String TAG = "ClassStatusAdapter";
    ClassStatusActivity context;
    List<ProClassStatus.DynamicBean> dynamicBean;


    public ClassStatusAdapter(ClassStatusActivity context, List<ProClassStatus.DynamicBean> dynamicBean) {
        super();
        this.dynamicBean = dynamicBean;
        this.context = context;
    }

    @Override
    public int getCount() {
        return dynamicBean.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.class_status_antivity_item, null);
            viewHolder.imgHead = (CircleImageView) convertView
                    .findViewById(R.id.imgHead);
            viewHolder.iv_video_pic = (ImageView) convertView
                    .findViewById(R.id.iv_video_pic);
            viewHolder.iv_small_class_video = (ImageView) convertView
                    .findViewById(R.id.iv_small_class_video);
            viewHolder.iv_class_album = (ImageView) convertView
                    .findViewById(R.id.iv_class_album);
            viewHolder.iv_video_share = (ImageView) convertView
                    .findViewById(R.id.iv_video_share);
            viewHolder.imb_video_play = (JCVideoPlayerStandard) convertView
                    .findViewById(R.id.imb_video_play);
            viewHolder.tvName = (TextView) convertView
                    .findViewById(R.id.tvName);
            viewHolder.tvContent = (TextView) convertView
                    .findViewById(R.id.tvContent);
            viewHolder.tvDate = (TextView) convertView
                    .findViewById(R.id.tvDate);
            viewHolder.gridview_pic = (GridView) convertView
                    .findViewById(R.id.gridview_pic);
            viewHolder.ivAgree = (ImageView) convertView
                    .findViewById(R.id.ivAgree);
            viewHolder.tvAgree = (TextView) convertView
                    .findViewById(R.id.tvAgree);
            viewHolder.tvComment = (TextView) convertView
                    .findViewById(R.id.tvComment);
            viewHolder.tv_look_people = (TextView) convertView
                    .findViewById(R.id.tv_look_people);
            viewHolder.ivComment = (ImageView) convertView
                    .findViewById(R.id.ivComment);
            viewHolder.relative_video_item = (RelativeLayout) convertView
                    .findViewById(R.id.relative_video_item);
            viewHolder.relative_item = (RelativeLayout) convertView
                    .findViewById(R.id.relative_item);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        //头像的设置
        if ("".equals(dynamicBean.get(position).getLogo()) || dynamicBean.get(position).getLogo() == null) {
            viewHolder.imgHead.setImageResource(R.drawable.touxiang);
        } else {
            Glide.with(context)
                    .load(BaseProtocol.IMG_BASE + dynamicBean.get(position).getLogo())
                    .error(R.drawable.touxiang)
                    .into(viewHolder.imgHead);
        }
        //发布者的名字
        viewHolder.tvName.setText(dynamicBean.get(position).getName());
        //点赞数目
        viewHolder.tvAgree.setText(dynamicBean.get(position).getGood() + "");
        //评论数目
        viewHolder.tvComment.setText(dynamicBean.get(position).getCommentNum() + "");
        //几人浏览过
        viewHolder.tv_look_people.setText(dynamicBean.get(position).getLookNum() + "人浏览");
        // 发布的内容 转换成utf-8
        String emocontent = "";
        try {
            emocontent = URLDecoder.decode(dynamicBean.get(position).getDetail(), "UTF-8");
        } catch (Exception e) {
            // TODO: handle exception
        }
        viewHolder.tvContent.setText(emocontent);
        //发布的时间  (解析时间戳)
        viewHolder.tvDate.setText(DateUtil.getDate(String.valueOf(dynamicBean.get(position).getLasttime())));

        if ("1".equals(dynamicBean.get(position).getMv_url())) {
            List<ProClassStatus.DynamicBean.ImgsBean> ImgsBean = dynamicBean.get(position).getImgs();
            final ArrayList imgList = new ArrayList();
            for (int i = 0; i < ImgsBean.size(); i++) {
                imgList.add(ImgsBean.get(i).getPath());
            }
            viewHolder.tv_look_people.setVisibility(View.VISIBLE);
            viewHolder.relative_video_item.setVisibility(View.GONE);
            viewHolder.gridview_pic.setVisibility(View.VISIBLE);
            viewHolder.iv_class_album.setVisibility(View.VISIBLE);
            viewHolder.iv_small_class_video.setVisibility(View.GONE);
            ImageGridAdapter gridAdapter = new ImageGridAdapter(ImgsBean);
            viewHolder.gridview_pic.setAdapter(gridAdapter);
            viewHolder.gridview_pic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(context,
                            AlbumImageBrowserActivity.class);
                    intent.putExtra("pos", position);
                    intent.putStringArrayListExtra("list", imgList);
                    context.startActivity(intent);
                }
            });
        } else {
            viewHolder.relative_video_item.setVisibility(View.VISIBLE);
            viewHolder.iv_small_class_video.setVisibility(View.VISIBLE);
            viewHolder.iv_class_album.setVisibility(View.GONE);
            viewHolder.gridview_pic.setVisibility(View.GONE);
            viewHolder.tv_look_people.setVisibility(View.INVISIBLE);
            Log.i(TAG, "getView: pic" + dynamicBean.get(position).getImg_url());

            if ("".equals(dynamicBean.get(position).getImg_url())) {
                viewHolder.imb_video_play.ivThumb.setImageResource(R.drawable.video_bg);
            } else {
                Glide.with(context)
                        .load(BaseProtocol.IMG_FRIST_BASE + dynamicBean.get(position).getImg_url())
                        .error(R.drawable.video_bg)
                        .into(viewHolder.imb_video_play.ivThumb);
            }
            //播放视频
            viewHolder.imb_video_play.setUp(BaseProtocol.VIDEO_BASE + dynamicBean.get(position).getMv_url(), "");
        }
        viewHolder.imgHead.setOnClickListener(new ListViewButtonOnClickListener(position));
        viewHolder.tv_look_people.setOnClickListener(new ListViewButtonOnClickListener(position));
        //点赞图片的监听
        viewHolder.ivAgree
                .setOnClickListener(new ListViewButtonOnClickListener(position));
        if (dynamicBean.get(position).getIscount() == 0) {
            viewHolder.ivAgree
                    .setImageResource(R.drawable.zan);
        } else {
            viewHolder.ivAgree
                    .setImageResource(R.drawable.iszan);
        }
        viewHolder.ivAgree.setFocusable(false);


        viewHolder.iv_video_share.setOnClickListener(new ListViewButtonOnClickListener(position));
        viewHolder.ivComment.setOnClickListener(new ListViewButtonOnClickListener(position));
        viewHolder.tvComment.setOnClickListener(new ListViewButtonOnClickListener(position));
        viewHolder.relative_item.setOnClickListener(new ListViewButtonOnClickListener(position));
        return convertView;
    }

    class ViewHolder {
        CircleImageView imgHead;  //头像
        ImageView ivAgree;  //是否点赞
        ImageView iv_video_pic;  //视频的第一帧图片
        ImageView iv_video_share;  //分享
        JCVideoPlayerStandard imb_video_play;  //视频的第一帧图片上的播放按钮
        ImageView iv_class_album;  //是班级相册的时候
        ImageView iv_small_class_video;  //是视频的时候
        ImageView ivComment;  //评论图片
        TextView tvName; //姓名
        TextView tvAgree; //点赞数量
        TextView tvComment; //评论数量
        TextView tvContent;//内容
        TextView tvDate;//发布时间
        TextView tv_look_people;//浏览过的人数量
        GridView gridview_pic; //图片的布局
        RelativeLayout relative_video_item; //视频
        RelativeLayout relative_item; //点击进入详情页
    }


    class ImageGridAdapter extends BaseAdapter {
        List<ProClassStatus.DynamicBean.ImgsBean> imgsBean;

        public ImageGridAdapter(List<ProClassStatus.DynamicBean.ImgsBean> imgsBean) {
            this.imgsBean = imgsBean;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imgsBean.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return imgsBean.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = LayoutInflater.from(context)
                        .inflate(R.layout.imggrid_item, null);
                holder.img_grid = (ImageView) convertView
                        .findViewById(R.id.imageView_imglist_item);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            Glide.with(context)
                    .load(BaseProtocol.IMG_BASE + imgsBean.get(position).getPath())
                    .into(holder.img_grid);
            return convertView;
        }
    }


    class ListViewButtonOnClickListener implements View.OnClickListener {
        private int position;// 记录ListView中Button所在的Item的位置
        private int num; //点赞的数量

        public ListViewButtonOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ivAgree:
                    ImageView ivAgree = (ImageView) v;
                    ProClassStatus.DynamicBean model = dynamicBean.get(position);
                    num = model.getGood();
                    if ("1".equals(dynamicBean.get(position).getMv_url())) {
                        if (model.getIscount() == 0) {
                            showClickGood(model.getJoinid());
                            ivAgree.setImageResource(R.drawable.iszan);
                            num++;
                            model.setGood(num);
                            model.setIscount(1);
                        } else {
                            showClickGoodCancle(model.getJoinid());
                            ivAgree.setImageResource(R.drawable.zan);
                            num--;
                            model.setGood(num);
                            model.setIscount(0);
                        }
                    } else {
                        if (model.getIscount() == 0) {
                            showVideoClickGood(model.getJoinid());
                            ivAgree.setImageResource(R.drawable.iszan);
                            num++;
                            model.setGood(num);
                            model.setIscount(1);
                        } else {
                            showVideoClickGoodCancle(model.getJoinid());
                            ivAgree.setImageResource(R.drawable.zan);
                            num--;
                            model.setGood(num);
                            model.setIscount(0);
                        }
                    }

                    dynamicBean.set(position, model);
                    notifyDataSetChanged();
                    break;
                case R.id.iv_video_share:
                    if ("1".equals(dynamicBean.get(position).getMv_url())) {

                        final String targeturl = BaseProtocol.IMG_SHARE
                                + dynamicBean.get(position).getJoinid();
                        String imglist_content = "";
                        try {
                            imglist_content = URLDecoder.decode(dynamicBean.get(position).getDetail(), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.isEmpty(imglist_content)) {
                            imglist_content = "班级相册";
                        }
                        String url = BaseProtocol.IMG_BASE
                                + dynamicBean.get(position).getImgs().get(0).getPath();
                        UmengShareUtil.shareUrl(context, "班级相册", imglist_content, url, targeturl);

                    } else {
                        //					Bitmap bitmap;
                        final String targeturl = BaseProtocol.VIDEO_SHARE
                                + dynamicBean.get(position).getJoinid();
                        final String url = BaseProtocol.IMG_FRIST_BASE
                                + dynamicBean.get(position).getImg_url();
                        String imglist_content = "";
                        try {
                            imglist_content = URLDecoder.decode(dynamicBean.get(position).getDetail(), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.isEmpty(imglist_content)) {
                            imglist_content = "班级视频";
                        }
                        UmengShareUtil.shareUrl(context, "班级视频", imglist_content, url, targeturl);
                    }

                    break;
                case R.id.imgHead:
                   Intent intent = new Intent(context, WorkOfTeacherActivity.class);
                    intent.putExtra("teacherid", dynamicBean.get(position).getUserid());
                    intent.putExtra("teachername", dynamicBean.get(position).getName());
                    context.startActivity(intent);
                    break;
                case R.id.relative_item:
                case R.id.tvComment:
                case R.id.ivComment:
                    intent = new Intent(context, ClassStatusItemDetailActivity.class);
                    intent.putExtra("tv_name", dynamicBean.get(position).getName());
                    intent.putExtra("tv_comment_num", dynamicBean.get(position).getCommentNum());
                    intent.putExtra("tv_detail", dynamicBean.get(position).getDetail());
                    intent.putExtra("tv_good", dynamicBean.get(position).getGood()); //赞数量
                    intent.putExtra("img_url", dynamicBean.get(position).getImg_url());
                    intent.putExtra("iscount", dynamicBean.get(position).getIscount());
                    intent.putExtra("joinid", dynamicBean.get(position).getJoinid());
                    intent.putExtra("iv_logo", dynamicBean.get(position).getLogo());
                    intent.putExtra("mv_url", dynamicBean.get(position).getMv_url());
                    intent.putExtra("tv_look_people", dynamicBean.get(position).getLookNum());
                    intent.putExtra("last_time", dynamicBean.get(position).getLasttime());
                    if ("1".equals(dynamicBean.get(position).getMv_url())) {
                        ArrayList imgList = new ArrayList();
                        ArrayList idList = new ArrayList();
                        for (int i = 0; i < dynamicBean.get(position).getImgs().size(); i++) {
                            imgList.add(dynamicBean.get(position).getImgs().get(i).getPath());
                            idList.add(dynamicBean.get(position).getImgs().get(i).getPath());
                        }
                        intent.putStringArrayListExtra("img_list", imgList);
                        intent.putStringArrayListExtra("id_list", idList);
                    }

                    context.startActivity(intent);
                    break;
                case R.id.tv_look_people:
                    intent = new Intent(context, LookPeopleNumActivity.class);
                    intent.putExtra("joinid", dynamicBean.get(position).getJoinid());
                    context.startActivity(intent);
                    break;
            }
        }
    }

    /**
     * 视频点赞的网络请求
     *
     * @param joinid
     */
    private void showVideoClickGood(int joinid) {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/mv/MvLook";
        } else {
            url = BaseProtocol.HOST_BASE + "/mv/MvLook";
        }
        //http://120.76.155.123:8080/api/mv/MvLook?userid=&mvid=
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("mvid", joinid);
        params.addParameter("userid", User.getUserLoginAccount(context));
        Log.i(TAG, "showVideoClickGood: joinid" + joinid);
        Log.i(TAG, "showVideoClickGood: USEid" + User.getUserLoginAccount(context));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProVideoShowClickGood proShowClickGood = new Gson().fromJson(result, ProVideoShowClickGood.class);
                if (proShowClickGood.getCode() == 0) {
                    Log.i(TAG, "onSuccess: 视频点赞成功");

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 视频取消点赞的网络请求
     *
     * @param joinid
     */
    private void showVideoClickGoodCancle(int joinid) {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/mv/MvCancel";
        } else {
            url = BaseProtocol.HOST_BASE + "/mv/MvCancel";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("mvid", joinid);
        params.addParameter("userid", User.getUserLoginAccount(context));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProVideoShowClickGoodCancle proVideoShowClickGoodCancle = new Gson().fromJson(result, ProVideoShowClickGoodCancle.class);
                if (proVideoShowClickGoodCancle.getCode() == 0) {
                    Log.i(TAG, "onSuccess: 视频取消点赞成功");
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 相册点赞的网络请求
     *
     * @param joinid
     */
    private void showClickGood(int joinid) {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/teacher/AlbumLook";
        } else {
            url = BaseProtocol.HOST_BASE + "/teacher/AlbumLook";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("albumid", joinid);
        params.addParameter("type", 2);
        params.addParameter("userid", User.getUserLoginAccount(context));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClickGood = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClickGood.getCode() == 0) {
                    Log.i(TAG, "onSuccess: 点赞成功");

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 相册取消点赞的网络请求
     *
     * @param joinid
     */
    private void showClickGoodCancle(int joinid) {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/teacher/AlbumCancel";
        } else {
            url = BaseProtocol.HOST_BASE + "/teacher/AlbumCancel";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("albumid", joinid);
        params.addParameter("userid", User.getUserLoginAccount(context));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGoodCancle proShowClickGoodCancle = new Gson().fromJson(result, ProShowClickGoodCancle.class);
                if (proShowClickGoodCancle.getCode() == 0) {
                    Log.i(TAG, "onSuccess: 取消点赞成功");

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    class Holder {
        ImageView img_grid;
    }
}
